package edu.cqie.common.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.cqie.common.anno.Authentication;
import edu.cqie.common.exception.BusinessException;
import edu.cqie.common.util.ApiResult;
import edu.cqie.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.lang.runtime.ObjectMethods;

/**
 * JWT令牌拦截器
 * 用于验证用户身份和权限
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class JwtTokenInterceptor implements HandlerInterceptor {

    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 如果不是处理方法直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 获取方法和类上的Authentication注解
        Authentication methodAnnotation = handlerMethod.getMethodAnnotation(Authentication.class);

        Authentication classAnnotation = handlerMethod.getBeanType().getAnnotation(Authentication.class);

        // 获取请求头中的token
        String token = request.getHeader("Authorization");

        try {
            // 解析JWT令牌
            Claims claims = JwtUtil.parsePayload(token);
            String userId = claims.get("userId", String.class);

            // 直接从JWT中获取用户
            String userAuthorization = claims.get("userAuthorization", String.class);

            log.info("用户JWT校验, 用户ID: {}, 权限: {}", userId, userAuthorization);

            //TODO 改造JWT 从redis或者获取部门权限信息 注解验权
            // 获取注解上的权限值
            String requiredPower = null;
            if (methodAnnotation != null) {
                requiredPower = String.valueOf(methodAnnotation.value());
            } else if (classAnnotation != null) {
                requiredPower = String.valueOf(classAnnotation.value());
            }

            // 权限判断
            if ("USER".equals(requiredPower) || requiredPower.equals(userAuthorization)) {
                return true;
            } else {

                throw  new BusinessException("权限不足", HttpStatus.UNAUTHORIZED);
            }
        } catch (Exception e) {

            throw  new BusinessException("无权限", HttpStatus.UNAUTHORIZED);

        }
    }

    /**
     * 将结果写入响应
     */
    private void writeResponse(HttpServletResponse response, ApiResult result) throws IOException {
        String jsonString = objectMapper.writeValueAsString(result);
        response.getWriter().write(jsonString);
    }
}
